import apiObj from './api';

class Http {
  constructor() {
    this.state = {};
  }
  use(state) {
    this.state = state.getState();
  }
  async get(url, data = {}, skipAuth) {
    console.log(this.state, 'this.state');
    try {
      const headers = new Headers();
      if (!skipAuth) {
        headers.append('Authorization', 'Bearer ' + 'token');
      }

      let query = '';
      Object.entries(data).forEach(([key, value], index) => {
        query += `${index === 0 ? '?' : '&'}${key}=${value}`;
      });
      const result = await new Promise((resolve, reject) => {
        let status = 0; // 0 d等待 1 完成 2 超时
        let timer = setTimeout(() => {
          if (status === 0) {
            status = 2;
            reject('Response timeout');
          }
        }, 15000); //响应超时时间
        fetch(apiObj.baseURL + url + query, {
          method: 'GET',
          headers,
        })
          .then(res => res.json())
          .then(res => {
            if (status === 0) {
              status = 1;
              clearTimeout(timer);
              timer = null;
              resolve(res);
            }
          });
      });
      switch (result.code) {
        case 200:
          return result.data;
        default:
          const resError = new Error(result.data.msg || result.data.message);
          resError.code = parseInt(result.data.code || result.data.status);
          return resError;
      }
    } catch (error) {
      //处理错误
      console.log('error....:', error);
    }
  }

  async post(url, data = {}, skipAuth) {
    try {
      const headers = new Headers();
      if (!skipAuth) {
        headers.append('Authorization', 'Bearer ' + 'token');
      }

      const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(data),
        headers,
      });
      const result = await response.json();
      if (result.code === 0) {
        return result;
      } else {
        //处理错误
      }
    } catch (error) {
      //处理错误
    }
  }
}

export const http = new Http();
export const api = apiObj;

export default {
  http,
  api,
};
